package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.USER_SIGN_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 没天赋
 * @since 2025-3-10
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final String CODE = "code";
    private final String USER = "user";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送短信验证码
     *
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //手机号不符合返回fail
            return Result.fail(ErrorConstants.PHONE_ERROR);
        }
        //2.生成验证码
        String code = RandomUtil.randomNumbers(6);
        //3.保存验证码到redis
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone,
                code, 2, TimeUnit.MINUTES);
        //4.发送验证码
        log.debug("发送验证码：{}", code);
        return Result.ok();
    }

    /**
     * 短信验证码登录
     *
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //手机号不符合返回fail
            return Result.fail(ErrorConstants.PHONE_ERROR);
        }
        //2.校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if (cacheCode == null || !cacheCode.equals(loginForm.getCode())) {
            //验证码验证错误
            return Result.fail(ErrorConstants.CODE_ERROR);
        }
        //3.根据手机号查询用户
        User user = query().eq("phone", phone).one();
        //4.如果用户不存在，则创建该用户
        if (user == null) {
            user = createUserWithPhone(loginForm);
            save(user);
        }
        //5.保存用户到redis
        //5.1 生成随机token作为令牌
        String token = UUID.randomUUID().toString(true);
        //5.2 将user对象转为hashmap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        //5.3 存储
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        //5.4 设置token有效期
        stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);
        //6.返回token
        return Result.ok(token);
    }

    /**
     * 用户签到
     *
     * @return
     */
    @Override
    public Result sign() {
        // 1.获取用户id
        Long userId = UserHolder.getUser().getId();
        // 2.获取时间
        LocalDateTime now = LocalDateTime.now();
        // 2.1.获取年月时间
        String yearAndMonth = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + yearAndMonth;
        // 2.2.获取当日是本月第几日
        int dayOfMonth = now.getDayOfMonth();
        // 3.签到写入Redis
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        // 4.返回
        return Result.ok();
    }

    /**
     * 统计连续签到次数
     *
     * @return
     */
    @Override
    public Result signCount() {
        // 1.获取用户id
        Long userId = UserHolder.getUser().getId();
        // 2.获取时间
        LocalDateTime now = LocalDateTime.now();
        // 2.1.获取年月时间
        String yearAndMonth = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + yearAndMonth;
        // 2.2.获取当日是本月第几日
        int dayOfMonth = now.getDayOfMonth();
        // 3.获取签到信息
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0)
        );
        if (result == null || result.isEmpty()) {
            return Result.ok(0);
        }
        // 4.获取信息并判空
        Long num = result.get(0);
        if (num == null || num == 0) {
            return Result.ok(0);
        }
        // 5.统计连续签到时间
        int count = 0;
        while ((num & 1) == 1) {
            num >>>= 1;
            count++;
        }
        // 6.返回
        return Result.ok(count);
    }

    /**
     * 通过手机号创建用户
     *
     * @param loginForm
     * @return
     */
    private User createUserWithPhone(LoginFormDTO loginForm) {
        return User.builder()
                .phone(loginForm.getPhone())
                .nickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(6))
                .build();
    }
}
